// Package utils
// @program: BannerStudioBlog.background
// @author: Hyy
// @create: 2021-10-28 21:11
package utils

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/astaxie/beego/logs"
	"github.com/dgrijalva/jwt-go"
)

// JWT : header payload signature
// json web token: 标头 有效负载 签名
const (
	SecretKEY            string = "BannerStudio"
	DefaultExpireSeconds int    = 600 // 默认10分钟
)

// MyCustomClaims
// This struct is the payload
// 此结构是有效负载
type MyCustomClaims struct {
	//UserID int `json:"userID"`
	//models.AuthUser
	jwt.StandardClaims
}

// JwtPayload
// This struct is the parsing of token payload
// 此结构是对令牌有效负载的解析
type JwtPayload struct {
	Username  string `json:"username"`
	UserID    int    `json:"userID"`
	IssuedAt  int64  `json:"iat"` // 发布日期
	ExpiresAt int64  `json:"exp"` // 过期时间
}

// ValidateToken
// @Title ValidateToken
// @Description "验证token"
// @Param tokenString 		string 	"编码后的token"
// @return   	*JwtPayload     "Jwt有效负载的解析"
// @return   	error         	"错误信息"
func ValidateToken(tokenString string) (map[string]interface{}, error) {
	tokenMap := make(map[string]interface{})
	if tokenString == "" {
		return tokenMap, errors.New("token令牌未输入")
	}
	mySigningKey, err := base64.RawURLEncoding.DecodeString(SecretKEY)
	if err != nil {
		logs.Error(err)
		return tokenMap, err
	}
	// 获取编码前的token信息
	token, err := jwt.Parse(
		tokenString,
		func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
				return nil, fmt.Errorf("unexepected siging method:%v", token.Header["alg"])
			}
			return mySigningKey, nil
		})
	if token != nil {
		claims, _ := token.Claims.(jwt.MapClaims)
		jsonClaim, err := json.MarshalIndent(claims, "", "\t")
		if err != nil {
			logs.Info(err)
			return tokenMap, err
		}
		err = json.Unmarshal(jsonClaim, &tokenMap)
		if err != nil {
			logs.Info(err)
			return tokenMap, err
		}
	}
	return tokenMap, nil
}
